<?php

/**
 * --------------------------------
 * Default TeacherRecordController
 *
 * 教师上课记录管理的统一类  TeacherRecordController
 * 
 * --------------------------------
 */
class TeacherRecordController extends BaseController{

	/**
     * 构造函数
     * 统一用户Session验证
     * 
     */
 /*   public function __construct(){
    	$check_result = Basecontroller::session('internal');
    	if(!$check_result) 
    		exit();
    }
*/





	/**
	 * 查询教师上课记录接口 
	 * @param
	 * @return Response
     *路由 Route::resource('teacher.record','TeacherRecordController'); 
     *method get
	 */
	public function index($teacher_id, $classes_id ='', 
                          $start_time='', $end_time='', 
                          $lesson_num='')
    {

        $start_time = Input::get('start_time');
        $end_time   = Input::get('end_time');
        $lesson_num = Input::get('lesson_num');
        $classes_id = Input::get('classes_id');
        
        $search_record = DB::table('ed_teacher_record')
               ->join('ed_classes','ed_teacher_record.classes_id','=','ed_classes.id')
               ->join('ed_school','ed_classes.school_id','=','ed_school.id')                  
               ->select('ed_teacher_record.*',
                        'ed_classes.name as classes_name',
                        'ed_school.name as school_name',
                        'ed_classes.student_num'
                        );

        if(''!= $classes_id){
            $search_record = $search_record->where('classes_id', '=', $classes_id);
        }

        if(''!= $lesson_num){
            $search_record = $search_record->where('ed_teacher_record.lesson_num', 
                                                   '=', $lesson_num);
        }

        //如果上课时间和下课时间都不为空，
        if(''!= $start_time && ''!= $end_time){
            $search_record = $search_record->where('ed_teacher_record.start_time', 
                                                   '<=',$start_time)
                                            ->where('ed_teacher_record.end_time', 
                                                    '<=',$end_time);
        }
        else if(''!= $start_time && ''== $end_time){//只有开始时间
            $search_record = $search_record->where('ed_teacher_record.start_time', 
                                                    '<=',$start_time);
        }
        else if(''== $start_time && ''!= $end_time){//只有下课时间
            $search_record = $search_record->where('ed_teacher_record.end_time', 
                                                   '<=',$end_time);
        }// if

        //搜索数据库
        try{
            $search_record = $search_record->where('ed_teacher_record.teacher_id',$teacher_id) 
                                           ->orderBy('created_at','desc')
                                           ->paginate(15)
                                           ->toJson();  
        }catch(Exception $e){
            return Response::json(['error'=>true, 'message'=>'运行错误']);
        }//try

		$record = json_decode($search_record);

        //如果记录为空
		if(empty($record->data)){
			return Response::json(['error'=>true,'message'=>'记录不存在']);
		}
		
        //获取每个上课记录的教学计划
        $this->get_teach_plan($record);

        return Response::json(['error'=>false,'result'=>$record]);
	                 
	}// function index()
    




    //获取上课记录中的教学计划
    public function get_teach_plan(&$record){

        foreach ($record->data as $key => $value) {
            //获取教学计划id
            $value->teach_plan = DB::table('ed_teacher_record_teach_plan')
                                   ->join('ed_teach_plan', 'ed_teach_plan.id', '=', 
                                          'ed_teacher_record_teach_plan.teach_plan_id'
                                          )
                                   ->where('teacher_record_id', '=', $value->id)
                                   ->select('teach_plan_id', 
                                            'ed_teach_plan.name as teach_plan_name'
                                            )
                                   ->get();
        }// foreach

    }// function get_teach_plan()







    /**
	 * 查询教师上课考勤接口 
	 * @param
	 * @return Response
     *路由 Route::resource('teacher.record','TeacherRecordController'); 
     *method get
	 */
	public function show($teacher_id, $id)
    {   

        try{
            //**************获取本次课堂记录的总体信息
            $result = DB::table('ed_teacher_record') 
                        ->join('ed_classes','ed_classes.id','=','ed_teacher_record.classes_id')
                        ->select(
                                'ed_teacher_record.*',
                                 'ed_classes.name as calss_name'
                                )
                        ->where('ed_teacher_record.id', '=', $id) 
                        ->first();

            $result = (array)$result;            
           //**************获取该教师上课记录的教学计划
           $result['teach_plan'] = DB::table('ed_teacher_record_teach_plan')
                      ->join('ed_teach_plan', 
                             'ed_teach_plan.id','=','ed_teacher_record_teach_plan.teach_plan_id')
                      ->where('teacher_record_id', '=', $id)
                      ->select(
                                'ed_teacher_record_teach_plan.teach_plan_id',
                                'ed_teach_plan.name as teach_plan_name'
                              )
                      ->get();

           //**************获取该教师上课记录的学生相关信息
           $result['student'] = DB::table('ed_student_record')
                                ->join('ed_student', 
                                       'ed_student.id', '=', 'ed_student_record.student_id')
                                ->where('ed_student_record.teacher_record_id', '=', $id)
                                ->select('ed_student_record.id',
                                         'ed_student.id as student_id',
                                         'ed_student.stuid',
                                         'ed_student.name',
                                         'ed_student.remain_lesson',
                                         'ed_student.remain_day',
                                         'ed_student.tel_mother',
                                         'ed_student.tel_father',
                                         'ed_student_record.is_attend',
                                         'ed_student_record.lesson_num',
                                         'ed_student_record.remark'
                                        )
                                ->get();

            //获取每个学生的具体上课教学计划信息
            foreach ($result['student'] as $key => $value) 
            {
               $value->teach_plan = DB::table('ed_stu_record_teach_plan')
                             ->join('ed_teach_plan',
                                    'ed_teach_plan.id',
                                    '=',
                                    'ed_stu_record_teach_plan.teach_plan_id'
                                    )
                             ->where('stu_record_id', '=', $value->id)
                             ->select(
                                      'ed_teach_plan.name as plan_name',
                                      'ed_stu_record_teach_plan.master_level',
                                      'ed_teach_plan.id as teach_plan_id'
                                      )
                             ->get();
            }//foreach


            return Response::json(['error'=>false, 'result'=>$result ]);

        }
        catch(Exception $e){
            return Response::json(['error'=>true, 'message'=>'数据库出错']);
        }//try

	}// function show()






	/**
	 * 新建教师上课考勤接口 
	 * @param
	 * @return Response
     *路由 Route::resource('teacher.record','TeacherRecordController'); 
     *method post
	 */
	public function store($teacher_id)
    {

        //检查有没有输入
        if( !Input::has('classes_id')   ||
            !Input::has('start_time')   ||
            !Input::has('end_time')     ||
            !Input::has('student')      ||          
            !Input::has('teach_plan')   ||
            !Input::has('date')         ||
            !Input::has('lesson_num')
            ){
            return Response::json(['error'=>true, 'message'=>'缺少重要信息']);
        }


        $new_teacher_record = array();      //用于存入ed_teacher_record表的数组
        $student_data = array();            //存储学生的上课信息
        $teach_plan_data = array();         //存储上课将的内容信息

        $student_data = Input::get('student');
        $teach_plan_data = Input::get('teach_plan');

        //获取班级的相关信息，后面计算消费什么的会用到
        $classes_id = Input::get('classes_id');
        $classes_data = DB::table('ed_classes')->where('id', '=', $classes_id)->get();


        $new_teacher_record['teacher_id']    = $teacher_id;
        $new_teacher_record['classes_id']    = Input::get('classes_id');
        $new_teacher_record['start_time']    = Input::get('start_time');
        $new_teacher_record['end_time']      = Input::get('end_time');
        $new_teacher_record['date']          = Input::get('date');
        $new_teacher_record['remark']        = Input::get('remark');
        $new_teacher_record['lesson_num']    = Input::get('lesson_num');
        //统计上课人数
        $attend_num = 0;
        foreach($student_data as $value) {
            if($value['is_attend']){
                $attend_num++;
            }
        }
        $new_teacher_record['student_attend_num'] = $attend_num;


        //**********************开启事务
        DB::beginTransaction();

        //*******在ed_teacher_record中存入一个教师上课记录，并生成一个teacher_record_id
        try{
             $new_teacher_record_id = DB::table('ed_teacher_record')
                                        ->insertGetId($new_teacher_record);   
        }catch(Exception $e){
            return Response::json(['error'=>true,'message'=>'存入ed_teacher_record表失败']);
        }


        //********信息存到ed_teacher_record_teach_plan(教师上课记录和教学计划关联表)中，
        //需要用到teacher_record_id，课上讲了多少个教学计划点就有多少条记录，用
        //foreach实现
        try{
            $new_teacher_record_teach_plan['teacher_record_id'] = $new_teacher_record_id;
            //插入数据库
            foreach ($teach_plan_data as $key => $value) {
                $new_teacher_record_teach_plan['teach_plan_id'] = $value['teach_plan_id'];
                DB::table('ed_teacher_record_teach_plan')
                  ->insert($new_teacher_record_teach_plan);
            }//foreach
        }
        catch(Exception $e){
            return Response::json(['error'=>true,'message'=>'存入ed_teacher_record_teach_plan表失败']);
        }


        //********信息存入ed_student_record（学生上课记录表）中，需要用到teacher_record_id
        //一节课可以有多个学生，一个学生只生成一条学生上课记录
        $new_student_record = array();      //用于存储即将存入ed_student_record的数据
        $new_stu_record_teach_plan = array();

        //student_data中有多个学生，用foreach实现存多个学生的上课记录
        foreach ($student_data as $key => $value) 
        {   
 
            $new_student_record['student_id'] = $value['student_id'];
            $new_student_record['teacher_id'] = $teacher_id;
            $new_student_record['classes_id'] = $new_teacher_record['classes_id'];
            $new_student_record['teacher_record_id'] = $new_teacher_record_id;
            $new_student_record['is_attend']  = $value['is_attend'];

            if(0 == $new_student_record['is_attend']){
              $value['lesson_num'] = 0;
            }

            $new_student_record['lesson_num'] = $value['lesson_num'];
            $new_student_record['remark']     = isset($value['remark'])?$value['remark']:"";

            try{
                //存入学生上课记录表中
                $new_student_record_id = DB::table('ed_student_record')
                                            ->insertGetId($new_student_record);
            }catch(Exception $e){
                DB::rollback();
                return Response::json(['error'=>true, 'message'=>'存入ed_student_record失败']);
            }

            //将信息存入到ed_stu_record_teach_plan（学生上课记录与教案关联表）中，
            //需要用到student_record_id
            //每条student_record对应多条ed_stu_record_teach_plan
            $new_stu_record_teach_plan['stu_record_id'] = $new_student_record_id;
            foreach ($value['teach_plan'] as $key2 => $value2) 
            {    

                $new_stu_record_teach_plan['teach_plan_id'] = $value2['teach_plan_id'];
                $new_stu_record_teach_plan['master_level']  = $value2['master_level'];
               
                try{
                    DB::table('ed_stu_record_teach_plan')->insert($new_stu_record_teach_plan);
                }catch(Exception $e){
                    DB::rollback();
                    return Response::json(['error'=>true, 'message'=>'存入ed_stu_record_teach_plan失败']);
                }

            }//foreach

            //在fi_account_record中添加消费记录
            //每个学生每次课只生成一条账户记录
            $new_account_record = array();
            $new_account_record['student_id'] = $value['student_id'];
            $new_account_record['name']       = $classes_data[0]->name.$value['lesson_num'].'学时';
            $new_account_record['time']       = Input::get('date');
            $new_account_record['type']       = '-';
            $new_account_record['cost_money'] = $classes_data[0]->lesson_tuition*$value['lesson_num'];
            $old_remain_money = DB::table('ed_student')
                                  ->where('id', '=', $value['student_id'])
                                  ->pluck('remain_money');
            $new_account_record['remain_money'] = $old_remain_money - $new_account_record['cost_money'];
            $new_account_record['student_record_id'] = $new_student_record_id;

            //fi_account_record中写入新记录
            try{
                DB::table('fi_account_record')->insert($new_account_record);
            }catch(Exception $e){
                //回滚事务
                DB::rollback();
                return Response::json(['error'=>true, 'message'=>'存入fi_account_record失败']);
            }   
                    
            try{
                //查询学生账户余额并进行修改
                $old_remain_money = DB::table('ed_student')
                                      ->where('id', '=', $value['student_id'])
                                      ->pluck('remain_money');
                $remain_money = $old_remain_money - $new_account_record['cost_money'];

                DB::update('update ed_student set remain_money='.$remain_money
                            .' where id='.$value['student_id']);

                //查询学生剩余课时并进行修改
                $old_remain_lesson = DB::table('ed_student')
                                      ->where('id', '=', $value['student_id'])
                                      ->pluck('remain_lesson');

                $remain_lesson = $old_remain_lesson - $new_student_record['lesson_num'];
                DB::update('update ed_student set remain_lesson='.$remain_lesson
                            .' where id='.$value['student_id']);

            }catch(Exception $e){
                //回滚事务
                DB::rollback();
                return Response::json(['error'=>true, 'message'=>'存入ed_student数据库失败']);
            }// try...catch
            
        }//foreach($student_data)

        //**********************提交事务
        DB::commit();    
        return Response::json(['error'=>false,'message'=>'成功录入']);

	}//function store()






  /**
   * 修改教师上课考勤接口 
   * @param
   * @return Response
     *路由 Route::resource('teacher/{教师id}/record{考勤记录id}','TeacherRecordController'); 
     *method put
   */
  public function update($teacher_id, $teacher_record_id)
  { 
    //**********************开启事务  
    DB::beginTransaction();
 //   try{
        //搜索出相关的学生上课记录
        $old_student_record = DB::table('ed_student_record')
                              ->where('teacher_record_id', '=', $teacher_record_id)
                              ->get();

        foreach ($old_student_record as $key => $value) {

          //*****将学生的消费余额和剩余课时数先加回来
          $student_update_array = array();  //存放学生的修改的信息
          $old_student = DB::table('ed_student')
                           ->where('id', '=', $value->student_id)
                           ->get();

          $money_data = DB::table('fi_account_record')
                          ->where('student_record_id', '=', $value->id)
                          ->select('cost_money', 'remain_money')
                          ->get();

          $student_update_array['remain_lesson'] = $old_student[0]->remain_lesson + 
                                                   $value->lesson_num;
          $student_update_array['remain_money']  = $money_data[0]->cost_money + 
                                                   $money_data[0]->remain_money;

          //将学生的消费余额和剩余课时数先加回来
          $is_success = DB::table('ed_student')
                          ->where('id', '=', $value->student_id)
                          ->update($student_update_array);      
          //操作是否成功，不成功则退出返回
          if(!$is_success){
            DB::rollback();
            return Response::json(['error'=>true, 'message'=>'1修改失败']);
          }

          //*****删除fi_account_record中的相关记录（即消费信息）
          $is_success = DB::table('fi_account_record')
                          ->where('student_record_id', '=', $value->id)
                          ->delete();
          //操作是否成功，不成功则退出返回
          if(!$is_success){
            DB::rollback();
            return Response::json(['error'=>true, 'message'=>'2修改失败']);
          }

          //*****删除ed_student_record_teach_plan中的相关记录
          $is_success = DB::table('ed_stu_record_teach_plan')
                          ->where('stu_record_id', '=', $value->id)
                          ->delete();
          //操作是否成功，不成功则退出返回
          if(!$is_success){
            DB::rollback();
            return Response::json(['error'=>true, 'message'=>'3修改失败']);
          }

          //*****删除ed_student_record中的相关记录
          $is_success = DB::table('ed_student_record')
                          ->where('id', '=', $value->id)
                          ->delete();
          //操作是否成功，不成功则退出返回
          if(!$is_success){
            DB::rollback();
            return Response::json(['error'=>true, 'message'=>'4修改失败']);
          }

      }// foreach
     // return Response::json(['teacher_record_id'=>$teacher_record_id]);
      //*****删除ed_teacher_record_teach_plan中的相关记录
      $is_success = DB::table('ed_teacher_record_teach_plan')
                      ->where('teacher_record_id', '=', $teacher_record_id)
                      ->delete();
      //操作是否成功，不成功则退出返回
      if(!$is_success){
        DB::rollback();
        return Response::json(['error'=>true, 'message'=>'5修改失败']);
      }

      //*****删除ed_teacher_record_teach_plan中的相关记录
      DB::table('ed_teacher_record')
        ->where('id', '=', $teacher_record_id)
        ->delete();
      //操作是否成功，不成功则退出返回
      if(!$is_success){
        DB::rollback();
        return Response::json(['error'=>true, 'message'=>'6修改失败']);
      }

      //*****调用store函数进行存入
      $this->store($teacher_id);

 /*   }//try
    catch(Exception $e){
      DB::rollback();
      return Response::json(['error'=>true, 'message'=>'运行出错，修改失败']);
    }
*/
    //**********************提交事务
    DB::commit();

    return Response::json(['error'=>false, 'message'=>'修改成功']);

  }// function update





  /**
   * 删除教师上课考勤接口 
   * @param
   * @return Response
     *路由 Route::resource('teacher.record','TeacherRecordController'); 
     *method DELETE
   */
  public function destroy($teacher_id, $teacher_record_id)
  { 
    //**********************开启事务  
    DB::beginTransaction();
  //  try{
        //搜索出相关的学生上课记录
        $old_student_record = DB::table('ed_student_record')
                              ->where('teacher_record_id', '=', $teacher_record_id)
                              ->get();

        foreach ($old_student_record as $key => $value) {

          //*****将学生的消费余额和剩余课时数先加回来
          $student_update_array = array();  //存放学生的修改的信息
          $old_student = DB::table('ed_student')
                           ->where('id', '=', $value->student_id)
                           ->get();

          $money_data = DB::table('fi_account_record')
                          ->where('student_record_id', '=', $value->id)
                          ->select('cost_money', 'remain_money')
                          ->get();

          //如果消费金额为0则不用更新了，否则程序出错
          if(0 !=$money_data[0]->cost_money){

            $student_update_array['remain_lesson'] = $old_student[0]->remain_lesson + 
                                                   $value->lesson_num;
            $student_update_array['remain_money']  = $money_data[0]->cost_money + 
                                                     $money_data[0]->remain_money;
    
            //将学生的消费余额和剩余课时数先加回来
            $is_success = DB::table('ed_student')
                            ->where('id', '=', $value->student_id)
                            ->update($student_update_array);      
            //操作是否成功，不成功则退出返回
            if(!$is_success){
              DB::rollback();
              return Response::json(['error'=>true, 'message'=>'1删除失败']);
            }

          }//if


          //*****删除fi_account_record中的相关记录（即消费信息）
          $is_success = DB::table('fi_account_record')
                          ->where('student_record_id', '=', $value->id)
                          ->delete();
          //操作是否成功，不成功则退出返回
          if(!$is_success){
            DB::rollback();
            return Response::json(['error'=>true, 'message'=>'2删除失败']);
          }

          //*****删除ed_student_record_teach_plan中的相关记录
          $is_success = DB::table('ed_stu_record_teach_plan')
                          ->where('stu_record_id', '=', $value->id)
                          ->delete();
          //操作是否成功，不成功则退出返回
          if(!$is_success){
            DB::rollback();
            return Response::json(['error'=>true, 'message'=>'3删除失败']);
          }

          //*****删除ed_student_record中的相关记录
          $is_success = DB::table('ed_student_record')
                          ->where('id', '=', $value->id)
                          ->delete();
          //操作是否成功，不成功则退出返回
          if(!$is_success){
            DB::rollback();
            return Response::json(['error'=>true, 'message'=>'4删除失败']);
          }

      }// foreach
  
      //*****删除ed_teacher_record_teach_plan中的相关记录
      $is_success = DB::table('ed_teacher_record_teach_plan')
                      ->where('teacher_record_id', '=', $teacher_record_id)
                      ->delete();
      //操作是否成功，不成功则退出返回

      if(!$is_success){
        DB::rollback();
        return Response::json(['error'=>true, 'message'=>'5删除失败']);
      }

      //*****删除ed_teacher_record_teach_plan中的相关记录
      DB::table('ed_teacher_record')
        ->where('id', '=', $teacher_record_id)
        ->delete();
      //操作是否成功，不成功则退出返回
      if(!$is_success){
        DB::rollback();
        return Response::json(['error'=>true, 'message'=>'删除失败']);
      }

  /*  }//try
    catch(Exception $e){
      DB::rollback();
      return Response::json(['error'=>true, 'message'=>'运行出错，修改失败']);
    }
*/
    //**********************提交事务
    DB::commit();

    return Response::json(['error'=>false, 'message'=>'删除成功']);
  }// function destroy



}//class